package cn.com.xinjinfu.pdoulcProduct.activity.login;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;

import android.view.View;
import android.widget.Button;

import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;


import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.widget.GestureEditActivity;

/**
 * 登录
 *
 * @author zqm
 */
public class LoginActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private final String ACTION_NAME = "跳转首页广播";
    private String mobile;
    private String pwd;
    private Dialog dg;

    private Button mLogin;
    private EditText mLoginPassword;
    private TextView tv_error_hint;

    private RequestQueue requen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ActivityManager.getInstance().addActivity(this);
        TitleManager.showTitle(this, "输入密码", "");
        requen = Volley.newRequestQueue(this);

        Intent intent = getIntent();
        mobile = intent.getStringExtra("mobile");
        initView();
    }

    private void initView() {
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        mLoginPassword = (EditText) findViewById(R.id.login_pwd_et);
        mLoginPassword.addTextChangedListener(mTextWatcher);
        findViewById(R.id.tv_forget_pwd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                intent.putExtra("mobile", mobile);
                startActivity(intent);
                finish();
            }
        });
        mLogin = (Button) findViewById(R.id.login_login_bt);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwd = mLoginPassword.getText().toString();
                loginRequest();
            }
        });
    }


    /**
     * 登录请求
     */
    public void loginRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters("1002");
        parameters.put("mobile", mobile);
        parameters.put("passwd", DataHandler.encrypt3DES(pwd));
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(LoginActivity.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("User+=================================" + jobj);
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                AccountManager.getInstance().saveUserInfoToFile(jobj);
                Intent intent = new Intent(LoginActivity.this, GestureEditActivity.class);
                intent.putExtra("flag", "0");
                startActivity(intent);

//                ActivityManager.getInstance().exitActivity();
//                Intent mIntent = new Intent(ACTION_NAME);
//                mIntent.putExtra("yaner", "shouye");
//                //发送广播
//                sendBroadcast(mIntent);
            } else {
                tv_error_hint.setText(JSONManager.getMsg(jobj));
            }
        }
    };

    /**
     * Editable 输入框光标一直在输入文本后面
     *
     * @param cb
     * @param flag
     */
    @Override
    public void onCheckedChanged(CompoundButton cb, boolean flag) {
        // TODO Auto-generated method stub
        if (flag) {
            mLoginPassword.setTransformationMethod(PasswordTransformationMethod
                    .getInstance());
        } else {
            mLoginPassword.setTransformationMethod(HideReturnsTransformationMethod
                    .getInstance());
        }
        // 输入框光标一直在输入文本后面
        Editable etable = mLoginPassword.getText();
        Selection.setSelection(etable, etable.length());
    }


    public void toast(String test) {
        Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            tv_error_hint.setText("");
            if (TextUtils.isEmpty(mLoginPassword.getText())) {
                mLogin.setEnabled(false);
            } else {
                mLogin.setEnabled(true);
            }
        }
    };
}